package com.lzy.cloud.job.utils;

import com.lzy.cloud.job.constants.CommonConstants.JobStatusEnum;
import com.lzy.cloud.job.dtos.JobInfoDto;
import com.lzy.cloud.job.quartz.BaseJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QuartzUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzUtil.class);

    public static void addJob(JobInfoDto myJob, Scheduler scheduler) throws SchedulerException {
        if (null == myJob || JobStatusEnum.OFF.equals(myJob.getStatus()))
            return;

        //
        TriggerKey triggerKey = TriggerKey.triggerKey(myJob.getJobName());
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

        // 不存在，创建一个
        if (null == trigger) {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            JobDetail jobDetail = JobBuilder.newJob(BaseJob.class)
                    .usingJobData("server-url", myJob.getServeId())
                    .usingJobData("server-method", myJob.getMethodName())
                    .build();
            CronScheduleBuilder cronExpression = CronScheduleBuilder.cronSchedule(myJob.getCronExpre());
            scheduler.scheduleJob(jobDetail, TriggerBuilder.newTrigger().withIdentity(myJob.getJobName()).withSchedule(cronExpression).build());
        } else {
            // trigger已存在，则更新相应的定时设置
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(myJob.getCronExpre());
            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }


}
